package com.pignest.framework.json;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * In official JSON parlance this should be called Object, however this would
 * cause confusion with {@link java.lang.Object} which is auto-imported.
 */
public class JsonObject extends JsonValue implements Map<String, JsonValue> {
	
	private final Map<String, JsonValue> proxy;
	
	public JsonObject() {
		proxy = new HashMap<String, JsonValue>();
	}
	
	public JsonObject(String... key) {
		this();
		if (key == null)
			return;
		for (int i = 0; i < key.length; i += 2) {
			put(key[i], key[i + 1]);
		}
	}
	
	@Override
	public String toExternalRepresentation() {
		StringBuffer output = new StringBuffer();
		output.append("{");

		boolean isFirst = true;
		for (Entry<String, JsonValue> entry : proxy.entrySet()) {
			if (isFirst) {
				isFirst = false;
			} else {
				output.append(", ");
			}

			output.append('\"');
			output.append(JsonString.escapeJavaScript(entry.getKey()));
			output.append("\":");
			output.append(entry.getValue().toExternalRepresentation());
		}
		output.append("} ");
		return output.toString();
	}

	public void clear() {
		proxy.clear();
	}

	public boolean containsKey(Object key) {
		return proxy.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return proxy.containsValue(value);
	}

	public Set<Entry<String, JsonValue>> entrySet() {
		return proxy.entrySet();
	}

	public JsonValue get(Object key) {
		return proxy.get(key);
	}

	public boolean isEmpty() {
		return proxy.isEmpty();
	}

	public Set<String> keySet() {
		return proxy.keySet();
	}

	public JsonValue put(String key, JsonValue value) {
		return proxy.put(key, value);
	}
	
	public JsonValue put(String key, String value) {
		return proxy.put(key, new JsonString(value));
	}
	
	public JsonValue put(String key, int value) {
		return proxy.put(key, new JsonInteger(value));
	}

	public void putAll(Map<? extends String, ? extends JsonValue> otherMap) {
		proxy.putAll(otherMap);
	}

	public JsonValue remove(Object key) {
		return proxy.remove(key);
	}

	public int size() {
		return proxy.size();
	}

	public Collection<JsonValue> values() {
		return proxy.values();
	}

	@Override
	public boolean equals(Object o) {
		return proxy.equals(o);
	}

	@Override
	public int hashCode() {
		return proxy.hashCode();
	}
}
